package com.servlet.album;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.util.DBUtil;
import com.view_object.UserVO;
import jdk.management.resource.ResourceContext;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.Track;
import java.io.IOException;
import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yuisama
 * @date 2023/03/12 14:28
 **/
@WebServlet("/studio/album/candidate.json")
public class CandidateJsonServlet extends HttpServlet {

    private  static  class TrackView{
        public Integer tid;
        public String title;

        @SneakyThrows
        public TrackView(ResultSet rs){
            this.tid = rs.getInt("tid");
            this.title = rs.getString("title");
        }
    }
    private static class ResultView{
        public UserVO currentUser;
        public String aid;
        public List<TrackView> trackList = new ArrayList<>();
    }
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aid = req.getParameter("aid");

        //判断登录用户的信息
        HttpSession session = req.getSession(false);
        if(session == null){
            throw new RuntimeException("未登录");
        }
        UserVO currentUser = (UserVO)session.getAttribute("currentUser");
        if(currentUser == null){
            throw new RuntimeException("未登录");
        }

        ResultView resultView = new ResultView();
        resultView.currentUser = currentUser;
        resultView.aid = aid;



        try(Connection c = DBUtil.connection()){
            String sql = "select tid,title from tracks where uid =? and tid in (select tid from relations where aid =?) order by tid desc";
            try(PreparedStatement ps = c.prepareStatement(sql)){
                ps.setInt(1,currentUser.uid);
                ps.setString(2,aid);


                try(ResultSet rs = ps.executeQuery()){
                    while(rs.next()){
                        resultView.trackList.add(new TrackView(rs));
                        //构造方法是直接传入rs，理论上这样不好，没有封装对象
                    }
                }
            }
        }
        // 4. JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(resultView);
        // 5. 响应
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}

